package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public User login(String username, String password) throws Exception {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = factory.openSession(true);
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user = userDao.findByUsernameAndPwd(username, password);
        sqlSession.close();
        return user;
    }

    @Override
    public List<User> findAll() throws Exception {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = factory.openSession(true);
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> list = userDao.findAll();
        sqlSession.close();
        return list;
    }
}
/*
    下次想换实现，不需要改动现有代码，直接写新的实现类即可  （开闭原则：对扩展开放，对修改关闭）
 */